#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
Author:Lijiacai
Email:1050518702@qq.com
===========================================
CopyRight@JackLee.com
===========================================
"""

import os
import sys
import json
import numpy as np


class CalWeight():
    def createFeatureMatrix(self, feature: dict):
        keys = []
        values = []
        for k, v in feature.items():
            keys.append(k)
            values.append(v)
        out = []
        for i in values:
            mid = []
            for j in values:
                mid.append(i / j)
            out.append(mid)
        return np.array(out), keys

    def cal_weight(self, feature: dict):
        matrix, keys = self.createFeatureMatrix(feature=feature)
        weight = self.get_w(matrix)
        return dict(zip(keys, weight))

    def get_w(self, array):
        RI_dict = {1: 0, 2: 0, 3: 0.58, 4: 0.90, 5: 1.12, 6: 1.24, 7: 1.32, 8: 1.41, 9: 1.45, 10: 1.49}
        # 1、计算出阶数 看这个数组是几维的 也就是后面对应字典查询！
        row = array.shape[0]
        # 2、按列求和
        a_axis_0_sum = array.sum(axis=0)
        # 3、得到新的矩阵b 就是把每一个数都除以列和
        b = array / a_axis_0_sum
        # 4、计算新矩阵b行和
        b_axis_1_sum = b.sum(axis=1)
        # 5、将b_axis_1_sum每一个值除以总和
        W = b_axis_1_sum / sum(b_axis_1_sum)
        # 6、将原始矩阵乘以W
        a_W = np.dot(array, W)
        # 7、求解最大特征值
        lambda_max = 0
        for i in range(len(a_W)):
            lambda_max += (a_W[i] / W[i])
        lambda_max = lambda_max / len(a_W)  # 求最大特征值
        # 8、检验判断矩阵的一致性
        C_I = (lambda_max - row) / (row - 1)
        R_I = RI_dict[row]
        C_R = C_I / R_I
        if C_R < 0.1:
            print('判断矩阵对应的最大特征值为 %.2f' % lambda_max)
            return W
        else:
            print('矩阵 %s 一致性检验未通过，需要重新进行调整判断矩阵' % (array))


if __name__ == '__main__':
    feature = {
        "avg_time": 5,
        "times": 8,
        "order_num": 6,
        "distance": 4,
        "return_num": 7
    }
    res = CalWeight().cal_weight(feature)
    print(res)
